use async_std::net::{TcpStream};
use async_std::io::{WriteExt};
use async_std::task;
pub enum HttpState{
    OK,  //200
    NotFound  //404
}
impl ToString for HttpState{  //从HttpState转为i32
    fn to_string(&self) -> String {
        match  self{
            HttpState::OK => "200 OK".to_string(),
            HttpState::NotFound =>"404 Not Found".to_string()
         }
    }
}
pub struct Response<'a>{
    http_head:String,
    body:String,
    writer:&'a TcpStream
}
impl<'a> Response<'a>{
    pub fn new(state:HttpState,stream:&'a TcpStream)->Self{
        let head: String = format!("HTTP/1.1 {} \r\n\
        Content-Type: text/html\r\n\
        \r\n",state.to_string());
        Response{
            http_head:head,
            body:String::new(),
            writer:stream
        }
    }
    pub fn send(&mut self,data:&[u8]){
        let _ = task::block_on(self.writer.write_all(self.http_head.as_bytes()));
        let _ = task::block_on(self.writer.write_all(data));
        println!("block_on");
    }
}
impl<'a> ToString for Response<'a>{
    fn to_string(&self) -> String {
        let mut http_response = String::new();
        http_response.push_str(&self.http_head);
        http_response.push_str(&self.body);
        http_response
    }
}